#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Purpose: Basic UI for the SDDP-Aquaplan add-in
# Created: 29/03/2010
# $Id $
# Copyright (c) 20010, Unesco-IHE
# Authors:
#  Didrik Pinte <dpinte@dipole-consulting.com>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with HydroPlatform for details.
import logging
import subprocess

from enthought.traits.api import HasTraits, Unicode, File, Button, \
     ListUnicode, Int, Dict, Enum, List, Str, ListStr, Bool, Directory, \
     Any
from enthought.traits.ui.api import View, Item, CheckListEditor, EnumEditor, \
     Group, HGroup
from enthought.traits.ui.menu import OKButton, CancelButton
from enthought.pyface.timer import do_later
from enthought.traits.ui.api import message

import export

class AquaplanInterface(HasTraits):
    """
    This is a dialog allowing to choose a network from a list 
    of networks, export the network to a file
    """
    network = Unicode(label="Network")
    networks = List
    
    session = Any
    
    output_file = File
    export = Button
    

    def __init__(self, **traits):
        """
        Overloading the default traits constructor
        """
        super(AquaplanInterface, self).__init__(**traits)
        if len(self.networks) > 0:
            self.network = self.networks[0]

    
    def _export_fired(self):
        """
        Export the selected network files
        """
        logging.debug("Export fired")
        do_later.do_later(self.export_to_file)
        
    def export_to_file(self):
        for network in self.session.hpproject.networks:
            if network.name == self.network:
                logging.info("Exporting %s" % self.network)
                exporter = export.AquaplanExporter()
                exporter.export(network, self.output_file, 
                        self.session.dbsession)
                message(message="Network exported successfully", title="Export")
                # FIXME : add an info about that
                return
        else:
            message(message="No network with this name", title="Export")
        
    
    traits_view = View(
        Group(
            Item("network", editor=EnumEditor(name="networks")),
            Item("output_file"),
            HGroup(
                Item("export", show_label=False),
            ),
            label="Parameters"
            ),
        resizable=True,
        buttons=[OKButton, CancelButton],
        title = "SDDP-Aquaplan"
    )
    
if __name__ == '__main__':
    t = AquaplanInterface(networks=['net1', 'net2', 'net3'])
    t.configure_traits()